package com.vdian.udc.apiadmin.common.ds;

import com.github.pagehelper.PageHelper;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @Title:数据源配置
 * @Description:TODO
 * @author:xu.he
 * @create:2017-02-15 11:40
 * @version:v1.0
 */
@Configuration
public class UdcApiAdminDataSource {

    @Value("${mybatis.uds.baseAliases}")
    private String udsBaseAliases;

    @Value("${mybatis.uds.resourcePath}")
    private String udsResourcePath;

    @Value("${datasource.type}")
    private Class<? extends DataSource> dataSourceType;

    /************** 初始化数据源 **************/
    @Bean
    @ConfigurationProperties(prefix = "datasource.uds.master")
    public HikariConfig udsMasterHikariConfig(){
        return new HikariConfig();
    }

    @Bean
    @ConfigurationProperties(prefix = "datasource.uds.slave")
    public HikariConfig udsSlaveHikariConfig(){
        return new HikariConfig();
    }

    @Bean(name="udsMasterDataSource")
    @ConfigurationProperties(prefix = "datasource.uds.master")
    public DataSource udsMasterDataSource(){
        return new HikariDataSource(udsMasterHikariConfig());
    }

    @Bean(name="udsSlaveDataSource")
    @ConfigurationProperties(prefix = "datasource.uds.slave")
    public DataSource udsSlaveDataSource(){
        return new HikariDataSource(udsSlaveHikariConfig());
    }

    /************** 初始化SqlSession **************/

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        return createSqlSessionFactory(roundRobinDataSource(),udsBaseAliases,udsResourcePath);
    }

    @Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name = "roundRobinDataSource")
    public AbstractRoutingDataSource roundRobinDataSource() {
        return new UdcApiAdminDataSourceRouter(udsMasterDataSource(),udsSlaveDataSource());
    }

    /**
     * 创建sqlsession方法
     * @param dataSource 数据源
     * @param baseAliases 实体类目录地址
     * @param resourcePath mapper文件地址
     * @return
     */
    private SqlSessionFactory createSqlSessionFactory(DataSource dataSource,String baseAliases,String resourcePath) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //设置javabean目录，mybatis会给java对象自动创建alias别名
        bean.setTypeAliasesPackage(baseAliases);
        //分页插件,插件无非是设置mybatis的拦截器
        Properties properties = new Properties();
        properties.setProperty("dialect", "mysql");
        //分页插件
        PageHelper pageHelper = new PageHelper();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
        //添加插件
        bean.setPlugins(new Interceptor[]{pageHelper});
        try {
            //添加XML目录
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] mapperResource=resolver.getResources(resourcePath);
            bean.setMapperLocations(mapperResource);
            SqlSessionFactory factory=bean.getObject();
            //mybatis全局设置
            factory.getConfiguration().setMapUnderscoreToCamelCase(true);
            return factory;
        } catch (Exception e) {
            throw new RuntimeException("sqlSessionFactory init fail",e);
        }
    }

}
